//
//  JsonHelper.m
//  HonlivHP
//
//  Created by admin on 2016/11/15.
//  Copyright © 2016年 honliv. All rights reserved.
//

#import "JsonHelper.h"

@implementation JsonHelper

+ (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    
    if(err) {
        
        NSLog(@"json解析失败：%@",err);
        
        return nil;
        
    }
    return dic;
}

+(NSArray *)arrayWithJsonString:(NSString *)jsonString{
    if (jsonString == nil|| jsonString == NULL) {
        return nil;
    }
    //去除控制符
    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
    NSRange range = [jsonString rangeOfCharacterFromSet:controlChars];
    if (range.location != NSNotFound){
        NSMutableString *mutable = [NSMutableString stringWithString:jsonString];
        while (range.location != NSNotFound) {
            [mutable deleteCharactersInRange:range];
            range = [mutable rangeOfCharacterFromSet:controlChars];
        }
        jsonString = mutable;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    NSArray *array = (NSArray *)[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return array;
}

@end
